package chat.server;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import chat.clientToServerMessage.ChangeRoom;
import chat.serverToClientMessage.ServerToClientMessage;


/**
 * 
 * @author Marius Eichenberg
 * a room contains a List of ClientThreads
 * and a List of the clientNames
 */
public class Room implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private String name;
	transient  List<ClientThread> clients = new LinkedList<ClientThread>();
	

	/**
	 * constructor to create a new room 
	 * @param roomID is given by a counter and its unique
	 * @param name name is temporally and can be changed
	 */
	public Room(String name) {
		this.name = name;
	}


	public String getName() {
		return name;
	}
	
	
	public void addClient(ClientThread ct){
		clients.add(ct);
	}
	
	
	public List<String> getUsernames(){
		List<String> userList = new LinkedList<String>();
		for(int i = 0; i < clients.size(); i++) {
			ClientThread ct = clients.get(i);
			String name = ct.getUsername();
			userList.add(name);
		}
		return userList;
	}
	
	
	/**
	 * Removes given Client
	 * @param ct
	 */
	public void removeClient(ClientThread ct) {
		int indexOfClientThread = clients.indexOf(ct);
		
		clients.remove(indexOfClientThread);
		//TODO: client_names.remove(ct.getClientID());
	}

	
	/**
	 * sents to all clients of these room
	 * @param messageToAll
	 */
	public void send(ServerToClientMessage messageToAll) {
		
			for(int i = 0; i < clients.size() ; i++) {
		       clients.get(i).send(messageToAll);
		}
	}


	public synchronized void setName(String newName) {
		this.name = newName;
	}


	public synchronized void changeAllToDefault(Server server) {
		for(int i = 0; i < clients.size() ; i++) {
		       ClientThread ct = clients.get(i);
		       ChangeRoom message = new ChangeRoom("default");
		       server.changeRoom(message, ct);
		}
	}
}
